#!/usr/bin/perl

use strict;
use warnings;

# tell Perl where to find MozComics package
BEGIN { push @INC, "../"; }

use MozComics::JSON;
use MozComics::MySQL;

use LWP::Simple;
use DateTime;
use DateTime::Format::Strptime;
use HTML::Entities qw(decode_entities);

# initialize comic object
my $guid = ''; # TODO
my $comic = MozComics::JSON->new($guid);
#my $comic = MozComics::MySQL->new($guid);
my $comicName = $comic->getName();
my $lastStripRow = $comic->getLastStrip();

# used to ensure that strips are put in the correct order
# (current 'strip' value should not be less than the previous 'strip' value)
my $lastStrip = 0;

my $dateParser = new DateTime::Format::Strptime(
	pattern => '%B %d, %Y',
	locale  => 'en_US'
);

# scrape information from a page
sub scrapePage { # TODO
	my $url = shift(@_) or die "$comicName: url not passed to scrapePage";
	my $page = shift(@_) or die "$comicName: page not passed to scrapePage";
	my $data = {};
	$data->{url} = $url;

	# scrape 'strip' value
	my $strip = 0;

	if($strip <= $lastStrip) {
		$strip = $lastStrip; #die "$comicName: $url is out of order?";
	}
	$strip += 1000;
	$lastStrip = $strip;
	$data->{strip} = $strip;

	# scrape 'title' value

	# scrape 'image' value

	return $data;
}

# ensure the data of the last strip has not changed
my $stripPage = get($lastStripRow->{url})
                or die "$comicName: last page url not found";
my $lastStripData = scrapePage($lastStripRow->{url}, $stripPage);
$comic->assertStripsEqual($lastStripData, $lastStripRow);

# reset $lastStrip value since it was changed in the previous scrapePage call
$lastStrip = $lastStripRow->{strip};

# follow "Next" links in order to find new strips
while($stripPage =~ //) { # TODO
	my $url = $1; # TODO
	$stripPage = get($url) or die "$comicName: next strip page not found";

	#print "$url\n";
	$comic->addStrip(scrapePage($url, $stripPage));
}

$comic->commit();

